package com.huike.task.service.impl;

import com.huike.common.config.MinioConfig;
import com.huike.common.constant.Constants;
import com.huike.common.core.redis.RedisCache;
import com.huike.task.service.ClearPdfService;
import io.minio.DeleteBucketLifecycleArgs;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Set;

@Service
public class ClearPdfServiceImpl implements ClearPdfService {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private MinioConfig minioConfig;

    @Override
    public void clearPdf() {
        System.out.println("开始清理...");
        Set<String> diff = redisCache.redisTemplate.opsForSet().
                difference(Constants.CONTRACT_NO_OSS, Constants.CONTRACT_NO_DB);
        System.out.println(diff);
        MinioClient minioClient = getClient();
        if (diff != null) {
//            minioClient.deleteBucketLifecycle(DeleteBucketLifecycleArgs.builder().build());
            try {
                for (String s : diff) {
                    String fileName = s.substring(10);
                    minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
                    System.out.println(fileName+" 被删除了");
                    redisCache.redisTemplate.opsForSet().remove(Constants.CONTRACT_NO_OSS, s);
                }
            } catch (ErrorResponseException e) {
                e.printStackTrace();
            } catch (InsufficientDataException e) {
                e.printStackTrace();
            } catch (InternalException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (InvalidResponseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (XmlParserException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 免费提供一个获取Minio连接的方法
     * 获取Minio连接
     * @return
     */
    private MinioClient getClient(){
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("http://"+minioConfig.getEndpoint()+":"+ minioConfig.getPort())
                        .credentials(minioConfig.getAccessKey(),minioConfig.getSecretKey())
                        .build();
        return minioClient;
    }
}
